package CCRMServer;

import java.io.IOException;

/** This class starts the CCRM server.
 * 
 * It connects to DB, and start listening
 * @author Ori Ziv
 *
 */
public class ServerStart {
	
	public static CCRMServer ccrm = null;

	/**
	 * This method init the server
	 * @param port
	 */
	public static void initCCRMServer (String port) {
		int serverProt = 11170;
		
		try {
			serverProt = Integer.parseInt(port);
		} catch (NumberFormatException e) {	}
		ccrm = new CCRMServer(serverProt);
		
		try {
			ccrm.listen();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * This main method allows running the system as a console application
	 * 
	 * @param args[0] name or IP address of the DB server
	 * @param args[1] DB name
	 * @param args[2] user name to connect to DB server
	 * @param args[3] password for the DB user
	 * @param args[4] optional argument: server's listening port. default is 11170
	 * 
	 * This method checks the command line syntax,
	 * sets the DB connection string
	 * and init the server to start listening
	 */
	public static void main(String[] args) {
		String usage = "Usage: java -jar CCRMServer DB_Server DB_name DB_user DB_password server_port(optional)";
		CCRMServer ccrm = null;
		
		// check command line syntax
		if (args.length < 4) {
			System.out.println(usage);
			System.exit(1);
		}
		
		// init DB connection
		DBConnect.setMySQLConnection(args[0], args[1], args[2], args[3]);
		
		// init server
		if (args.length == 5) {
			try {
				int serverProt = Integer.parseInt(args[4]);
				ccrm = new CCRMServer(serverProt);
			} catch (NumberFormatException e) {
				System.out.println(usage);
				e.printStackTrace();
			}
		} else
			ccrm = new CCRMServer();
		
		try {
			ccrm.listen();
		} catch (IOException e) {
			System.out.println("ERROR: Srever could not start");
			System.exit(1);
		}			
	} // End of method main
}// end of class ServerStart
